<?php
class Organization_Controller extends AdminController {

    public $DISPLAY_PERSON_LIST_UUID = 'admin/organization/display/personList';
    public $DISPLAY_REP_LIST_UUID = 'admin/organization/display/repList';
    
    public function __construct() {
        parent::__construct('organization');
        $this->setDefaultListOrder('name');
    }
    
    function all() {
        $this->initPagination('organization');

        $this->viewData['organizationList'] = $this->dao->queryAll($this->orderLimitAndOffset(
                'SELECT org.*, c.name AS country_name, p.first_name, p.last_name ' .
                'FROM organization org ' .
                'LEFT OUTER JOIN person p ON p.id = org.organizer_id ' .
                'LEFT OUTER JOIN country c ON c.code = org.country_code'
        ));
        $this->renderSubview('admin/organization/organizationList');
    }
    
    function display() {
        $id = $this->input->get('id');
        
        if (! valid::isId($id)) {
            $this->redirectToList('error.invalidId');
        }

        $organization = $this->dao->getOrganization($id);
        if (! $organization) {
            $this->redirectToList('error.recordNotFound');
        }
        $this->viewData['organization'] = $organization;

        if (! request::is_ajax()) {
            $this->viewData['memberList'] = $this->dao->orderedOrgMembers($id, $this->DISPLAY_PERSON_LIST_UUID);
            $this->viewData['representativeList'] = $this->dao->orderedOrgRepresentatives($id, $this->DISPLAY_REP_LIST_UUID);
            $this->viewData['addRepAcValues'] = $this->dao->optionsOrganizationRepCandidate($id);
        }
        
        $this->renderSubview('admin/organization/organizationDisplay');
    }
    
    function addRepresentative() {
        $id = $this->input->post('id');
        $personId = $this->input->post('person_id');

        if (! valid::isId($id) || ! valid::isId($personId)) {
            $this->redirectToList('error.invalidId');
        }

        $organization = $this->dao->getOrganization($id);
        if (! $organization) {
            $this->redirectToList('error.recordNotFound');
        }

        $person = $this->dao->fetchPersonById($personId);
        if (! $person) {
            $this->msg->error('error.recordNotFound');
            $this->redirect('/admin/organization/display?id=' . $id);
        }

        $this->dao->insert('organization_rep', array('person_id' => $personId, 'organization_id' => $id));

        $this->msg->info('organization.addRepSuccess', format::personFullName($person));
        $this->redirect('/admin/organization/display?id=' . $id);
    }
    
    public function removeRepresentative() {
        $id = $this->input->get('id');
        $personId = $this->input->get('person_id');

        if (! valid::isId($id) || ! valid::isId($personId)) {
            $this->redirectToList('error.invalidId');
        }

        $organization = $this->dao->getOrganization($id);
        if (! $organization) {
            $this->redirectToList('error.recordNotFound');
        }

        $person = $this->dao->fetchPersonById($personId);
        if (! $person) {
            $this->msg->error('error.recordNotFound');
            $this->redirect('/admin/organization/display?id=' . $id);
        }

        $this->dao->executeQuery(
                'DELETE FROM organization_rep WHERE person_id = :person_id AND organization_id = :organization_id',
                array('person_id' => $personId, 'organization_id' => $id));

        $this->msg->info('organization.removeRepSuccess', format::personFullName($person));
        $this->redirect('/admin/organization/display?id=' . $id);
    }
    
    function edit() {
        $id = $this->input->get('id');
        $organization = array();
        
        if ($id) {
            $organization = $this->dao->getById('organization', $id);
            if (! $organization) {
                $this->redirectToList('error.recordNotFound');
            }
        }
        else {
            // Set default insert values here
        }
        
        $this->loadFormData();
        
        $this->viewData['organization'] = $organization;
        $this->renderSubview('admin/organization/organizationEdit');
    }
    
    protected function loadFormData() {
        $this->viewData['countryOptions'] = $this->dao->optionsCountry();
        $this->viewData['organizerAcValues'] = $this->dao->queryOptions(
                'SELECT id, last_name, first_name, birth_date FROM person ', null, array(' ', '()'));
    }
    
    function save() {
        $organization = $this->postToDbValues();
        $id = $organization['id'];
        $this->viewData['organization'] = $organization;
        
        // Basic validation
        $validator = new EntityValidator($organization, 'organization', $this->msg);
        $validator->required('name');
        $validator->boolean('emails_enabled');
        $validator->required('country_code');
        $validator->applicationLanguage('preferred_language');
        
        if ($this->msg->hasErrors()) {
            $this->loadFormData();
            $this->renderSubview('admin/organization/organizationEdit');
            return;
        }

        // Database validation
        if ($organization['name'] && $this->dao->alreadyExists('organization', 'name', $organization)) {
            $this->loadFormData();
            $this->msg->error('organization.error-alreadyExists-name', $organization['name']);
            $this->renderSubview('admin/organization/organizationEdit');
            return;
        }
        
        // Insert/update
        if (sql::isPersistent($organization)) {
            $this->dao->update('organization', $organization, 'id', array('organizer'));
            $this->msg->info('organization.editSuccess', $organization['name']);
        }
        else {
            $id = $this->dao->insert('organization', $organization, array('organizer'));
            $this->msg->info('organization.createSuccess', $organization['name']);
        }
        
        $this->redirectToList();
    }
    
    function delete() {
        $id = $this->input->get('id');
        
        // Basic validation
        if (! valid::isId($id)) {
            $this->redirectToList('error.invalidId');
        }
        
        $organization = $this->dao->getById('organization', $id);
        if (! $organization) {
            $this->redirectToList('error.recordNotFound');
        }

        $this->dao->delete('organization', $id);
        
        $this->msg->info('organization.deleteSuccess', $organization['name']);
        $this->redirectToList();
    }
}
?>
